package com.jilujia.web.controller;

import java.security.Principal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;

import com.jilujia.domain.user.User;
import com.jilujia.domain.user.service.UserService;
import com.jilujia.framework.exception.ForbiddenOperatorException;
import com.jilujia.framework.exception.ResourceNotFoundException;
import com.jilujia.framework.security.JilujiaUser;
import com.jilujia.framework.web.AbstractController;

public class AbstractWebController extends AbstractController {

	@Autowired
	private UserService userService;

	/**
	 * 根据currentUser和userId返回User.
	 * <p>
	 * <li>如果user不存在，抛出ResourceNotFoundException.</li>
	 * <li>如果user和currentUser不一致，抛出ForbiddenOperatorException.</li>
	 * </p>
	 * 
	 * @param currentUser
	 *            当前user的Principal
	 * @param userId
	 *            userId
	 * @return 合法的User
	 */
	public User findUserByCurrentUserAndUserId(Principal currentUser, Long userId) {
		User user = userService.findEnabledUser(userId);
		if (user == null) {
			throw new ResourceNotFoundException(userId);
		}

		// check belong to?
		JilujiaUser currentRealUser = findUserByCurrentUser(currentUser);
		if (currentRealUser.getUserId().longValue() != userId.longValue()) {
			throw new ForbiddenOperatorException(userId);
		}
		return user;
	}

	public JilujiaUser findUserByCurrentUser(Principal currentUser) {
		// check belong to?
		JilujiaUser currentRealUser = (JilujiaUser) ((Authentication) currentUser).getPrincipal();
		return currentRealUser;
	}
}
